package deliciouse.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import deliciouse.dao.CategoryDao;
import deliciouse.dao.FoodDao;
import deliciouse.dao.impl.CategoryDaoImpl;
import deliciouse.dao.impl.FoodDaoImpl;
import deliciouse.entity.Category;
import deliciouse.entity.Food;

@WebServlet("/productlist")
public class FoodListServlet extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String title = null;
		int cid = 0;
		if (request.getParameter("cid") != null && !request.getParameter("cid").isEmpty())
			cid = Integer.valueOf(request.getParameter("cid"));
		if (request.getParameter("title") != null && !request.getParameter("title").isEmpty()) {
			title = request.getParameter("title");
		} else {
			title = "";
		}
		FoodDao foodDao = new FoodDaoImpl();
		CategoryDao categorydao = new CategoryDaoImpl();
		int pageSize = 8;
		int pageNum = 1;
		if (request.getParameter("pageNum") != null && !request.getParameter("pageNum").isEmpty())
			pageNum = Integer.valueOf(request.getParameter("pageNum"));
		int pageNumMax = foodDao.getAllRows(cid, title) % pageSize == 0 ? foodDao.getAllRows(cid, title) / pageSize
				: foodDao.getAllRows(cid, title) / pageSize + 1;

		List<Food> list = foodDao.fetchByCondition(cid, title, pageNum, pageSize);
		List<Category> categorylist = categorydao.getAll();
		request.setAttribute("cid", cid);
		request.setAttribute("title", title);
		request.setAttribute("pageNum", pageNum);
		request.setAttribute("pageNumMax", pageNumMax);
		request.setAttribute("list", list);
		request.setAttribute("categorylist", categorylist);
		request.getRequestDispatcher("productlist.jsp").forward(request, response);
	}

}
